package fr.smile.liferay.portlet.news.util;

import java.util.List;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.xml.Document;
import com.liferay.portal.kernel.xml.Element;
import com.liferay.portal.kernel.xml.SAXReaderUtil;

public class LocaleTransformer {
	private static final Log LOG = LogFactoryUtil.getLog(LocaleTransformer.class);

	private final String _languageId;
	
	public LocaleTransformer(String languageId) {
		this._languageId = languageId;
	}

	public String onXml(String s) {
		s = replace(s);

		return s;
	}

	protected String replace(String xml) {
		if (xml == null) {
			return xml;
		}

		try {
			Document doc = SAXReaderUtil.read(xml);

			Element root = doc.getRootElement();

			String defaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

			String[] availableLocales = StringUtil.split(
				root.attributeValue("available-locales", defaultLanguageId));

			String defaultLocale = root.attributeValue(
				"default-locale", defaultLanguageId);

			boolean isSupportedLocale = false;

			for (int i = 0; i < availableLocales.length; i++) {
				if (availableLocales[i].equalsIgnoreCase(_languageId)) {
					isSupportedLocale = true;
					break;
				}
			}

			replace(root, !isSupportedLocale ? defaultLocale : _languageId);

			xml = doc.formattedString("  ");
		}
		catch (Exception e) {
			LOG.error(e);
		}

		return xml;
	}

	protected void replace(Element root, String languageId) {
		List<Element> children = root.elements();

		int listIndex = children.size() - 1;
		while (listIndex >= 0) {
			Element child = children.get(listIndex);

			String childLanguageId = child.attributeValue("language-id", languageId);
			if (!childLanguageId.equalsIgnoreCase(languageId)) {
				root.remove(child);
			} else {
				replace(child, languageId);
			}

			listIndex--;
		}
	}
}
